document.addEventListener('DOMContentLoaded', function () {
    getUserID().then(userId => {
        if (userId!== "not_logged_in") {
            loadCartItems(userId);
        } else {
            alert('用户未登录');
        }
    });
});

// 获取用户ID
function getUserID() {
    return fetch('/api/get-user-id', {
        credentials: 'include'
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Failed to fetch user ID');
            }
            return response.text();
        })
        .catch(error => {
            console.error('Error fetching user ID:', error);
            alert('无法获取用户ID');
            return Promise.resolve("not_logged_in");
        });
}

// 加载购物车项
function loadCartItems(userId) {
    fetch(`/api/cart/items?userId=${userId}`, {
        credentials: 'include'
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Failed to fetch cart items');
            }
            return response.json();
        })
        .then(cartItems => {
            const cartItemsContainer = document.getElementById('cartItems');
            let total = 0;

            cartItemsContainer.innerHTML = ''; // 清空现有的购物车项

            cartItems.forEach(cartItem => {
                fetch(`/api/products/${cartItem.productId}`, {
                    credentials: 'include'
                })
                    .then(response => response.json())
                    .then(product => {
                        if (product) {
                            const decodedName = decodeURIComponent(product.name || '');
                            const price = parseFloat(product.price) || 0;
                            const quantity = parseInt(cartItem.quantity, 10) || 1;

                            const itemElement = document.createElement('div');
                            itemElement.className = 'cart-item';
                            itemElement.dataset.cartItemId = cartItem.id;
                            itemElement.innerHTML = `
                    <img src="${product.imageURL}" alt="${decodedName}" class="item-image" />
                    <div class="item-details">
                        <input type="checkbox" class="item-select" /> <!-- 默认不勾选 -->
                        <span class="item-name">${decodedName}</span>
                        <span class="item-price">$${price}</span>
                    </div>
                    <div class="item-quantity-container">
                        <button class="decrease-qty">-</button>
                        <input type="number" class="item-quantity" value="${quantity}" min="1" max="99" />
                        <button class="increase-qty">+</button>
                    </div>
                    `;
                            cartItemsContainer.appendChild(itemElement);

                            const decreaseQtyBtn = itemElement.querySelector('.decrease-qty');
                            const increaseQtyBtn = itemElement.querySelector('.increase-qty');
                            const quantityInput = itemElement.querySelector('.item-quantity');
                            const selectCheckbox = itemElement.querySelector('.item-select');

                            decreaseQtyBtn.addEventListener('click', function () {
                                let quantity = parseInt(quantityInput.value, 10);
                                if (quantity > 1) {
                                    quantity--;
                                    quantityInput.value = quantity;
                                    updateCartQuantity(userId, cartItem.id, quantity);
                                }
                            });

                            increaseQtyBtn.addEventListener('click', function () {
                                let quantity = parseInt(quantityInput.value, 10);
                                quantity++;
                                quantityInput.value = quantity;
                                updateCartQuantity(userId, cartItem.id, quantity);
                            });

                            quantityInput.addEventListener('input', function () {
                                const quantity = parseInt(this.value, 10);
                                if (isNaN(quantity) || quantity < 1 || quantity > 99) {
                                    // 如果输入不符合要求，恢复原来的值
                                    const originalQuantity = parseInt(this.dataset.originalQuantity, 10);
                                    this.value = originalQuantity;
                                    return;
                                }
                                this.dataset.originalQuantity = this.value;
                                updateCartQuantity(userId, cartItem.id, quantity);
                            });

                            selectCheckbox.addEventListener('change', function () {
                                updateTotal();
                            });

                            // 计算总价
                            if (selectCheckbox.checked) {
                                total += price * quantity;
                            }
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching product details:', error);
                        alert('无法加载商品详情');
                    });
            });

            document.getElementById('totalPrice').textContent = total.toFixed(2);
        })
        .catch(error => {
            console.error('Error fetching cart items:', error);
            alert('无法加载购物车数据');
        });
}

function updateTotal() {
    const cartItems = document.querySelectorAll('.cart-item');
    let total = 0;
    cartItems.forEach(item => {
        const selectCheckbox = item.querySelector('.item-select');
        const quantityInput = item.querySelector('.item-quantity');
        const priceElement = item.querySelector('.item-price');
        const price = parseFloat(priceElement.textContent.replace('$', ''));
        const quantity = parseInt(quantityInput.value, 10);

        if (selectCheckbox.checked) {
            total += price * quantity;
        }
    });
    document.getElementById('totalPrice').textContent = total.toFixed(2);
}

// Event listeners for manage, confirm, and cancel buttons
const manageButton = document.getElementById('manageButton');
const confirmDeleteButton = document.getElementById('confirmDeleteButton');
const cancelDeleteButton = document.getElementById('cancelDeleteButton');

manageButton.addEventListener('click', function () {
    document.querySelectorAll('.item-select').forEach(checkbox => {
        checkbox.disabled = false;
    });
    manageButton.style.display = 'none';
    confirmDeleteButton.style.display = 'inline';
    cancelDeleteButton.style.display = 'inline';
});

confirmDeleteButton.addEventListener('click', function () {
    getUserID().then(userId => {
        if (userId === "not_logged_in") {
            alert('用户未登录');
            return;
        }

        const selectedCartItems = document.querySelectorAll('.cart-item.item-select:checked');
        if (selectedCartItems.length === 0) {
            alert('请选择要删除的商品');
            return;
        }

        const cartItemIds = [];
        selectedCartItems.forEach(checkbox => {
            const cartItemElement = checkbox.closest('.cart-item');
            const cartItemId = cartItemElement.dataset.cartItemId;
            if (cartItemId) {
                cartItemIds.push(cartItemId);
                deleteCartItem(userId, cartItemId); // 传递正确的 cartItemId
            }
        });

        // Hide manage controls
        manageButton.style.display = 'inline';
        confirmDeleteButton.style.display = 'none';
        cancelDeleteButton.style.display = 'none';
        document.querySelectorAll('.item-select').forEach(checkbox => {
            checkbox.disabled = true;
            checkbox.checked = false;
        });
    });
});

cancelDeleteButton.addEventListener('click', function () {
    manageButton.style.display = 'inline';
    confirmDeleteButton.style.display = 'none';
    cancelDeleteButton.style.display = 'none';
    document.querySelectorAll('.item-select').forEach(checkbox => {
        checkbox.disabled = true;
        checkbox.checked = false;
    });
});

// Delete cart item
function deleteCartItem(userId, cartItemId) {
    fetch(`/api/cart/delete?userId=${userId}&cartItemId=${cartItemId}`, {
        method: 'DELETE',
        credentials: 'include'
    })
        .then(response => {
            if (response.ok) {
                alert('Item deleted');
                loadCartItems(userId); // Reload cart items after deletion
            } else {
                throw new Error('Failed to delete item');
            }
        })
        .catch(error => {
            console.error('Error deleting cart item:', error);
            alert('删除购物车商品时发生错误');
        });
}

// Checkout function
function checkout() {
    getUserID().then(userId => {
        if (userId === "not_logged_in") {
            alert('用户未登录');
            return;
        }

        // 获取所有选中的商品项
        const cartItemIdsToCheckout = [];
        document.querySelectorAll('.cart-item').forEach(item => {
            const checkbox = item.querySelector('.item-select');
            if (checkbox.checked) { // 确保只添加勾选的商品项
                const id = item.dataset.cartItemId;
                if (id) {
                    cartItemIdsToCheckout.push(id); // 直接推入 ID
                }
            }
        });

        if (cartItemIdsToCheckout.length === 0) {
            alert('请选择要结账的商品项');
            return;
        }

        // 弹出确认对话框
        const confirmPayment = confirm('确定要付款吗？');
        if (confirmPayment) {
            const totalAmount = parseFloat(document.getElementById('totalPrice').textContent);

            // 发起结账请求，结账流程中包含创建订单的逻辑
            fetch('/api/cart/checkout', {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    userId: userId,
                    cartItemIds: cartItemIdsToCheckout, // 传递 ID 数组
                    totalAmount: totalAmount
                })
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('结账失败');
                    }
                    return response.json();
                })
                .then(data => {
                    // 假设服务器返回了 orderId
                    const orderId = data.orderId;
                    // 结账成功后，重定向到确认订单页面
                    window.location.href = `/ConfirmOrder.html?orderId=${orderId}`;
                })
                .catch(error => {
                    console.error('Error during checkout:', error);
                    alert('结账失败');
                });
        } else {
            // 如果用户取消，不做任何操作
        }
    });
}

function updateCartQuantity(userId, cartItemId, newQuantity) {
    const url = `/api/cart/update?userId=${encodeURIComponent(userId)}&cartItemId=${encodeURIComponent(cartItemId)}&newQuantity=${encodeURIComponent(newQuantity)}`; // 修正 URL 拼接
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        credentials: 'include'
    })
        .then(response => {
            if (response.ok) {
                alert('Quantity updated');
            } else {
                throw new Error('更新购物车数量失败');
            }
        })
        .catch(error => {
            console.error('Error updating cart quantity:', error);
            alert('更新购物车数量时发生错误');
        });
}